package com.lcf.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginIntercept implements HandlerInterceptor {

    /**
     * 问题：preHandle里的消息打印两次？？？
     * 调用的接口：http://localhost:8080/index2?name=zhangsan
     *原因：在controller中没有index2这个请求路径，但是有name属性，所以preHandle返回true
     * 因为preHandle返回true，它就去向下执行，去找对应的处理器，没有找到，又发出error请求，又被拦截一次。
     * 这也向我们展示了拦截器和处理器执行的顺序，是拦截器preHandle方法在前，处理器在后的，
     * preHandle方法执行时并不知道现在的整个请求有没有对应的处理器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle被调用");
//        Map map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
//        System.out.println(map.get("name"));
        System.out.println(request.getParameter("name"));
        if (request.getParameter("name").equals("zhangsan")) {
            return true;    //如果false，停止流程，api被拦截
        } else {
            PrintWriter printWriter = response.getWriter();
            printWriter.write("please login again!");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
